package com.winit.openapi.apiadapter.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.pms.spi.v2.base.BaseVasRelService;
import com.winit.pms.spi.v2.base.command.BaseVasRelQueryCommand;
import com.winit.pms.spi.v2.base.vo.BaseAttrRelVo;
import com.winit.pms.spi.v2.base.vo.BaseVasRelVo;
import com.winit.pms.spi.v2.base.vo.PlanEventVo;
import com.winit.pms.spi.v2.common.PmsConstants;
import com.winit.pms.spi.v2.common.PmsEnumType;
import com.winit.pms.spi.v2.instance.pscInstance.ProductInstanceService;
import com.winit.pms.spi.v2.instance.pscInstance.command.ProductLogisticsCommand;
import com.winit.pms.spi.v2.instance.pscInstance.vo.ProductInstance;
import com.winit.pms.spi.v2.vo.LogisticsDist;
import com.winit.ups.spi.command.QueryWarehouseByTypesCommand;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.command.QueryWarhouseByIdCommand;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

/**
 * ERP查询派送方式接口<queryDeliveryWay>适配
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2016年11月24日 	Created
 *
 * </pre>
 */
@Controller
public class DeliveryWayAdapteController extends AbstractAdapteController {

    @Resource
    private ProductInstanceService productInstanceService;

    @Resource
    private WarehouseService       upsWarehouseService;
    @Resource
    private BaseVasRelService      baseVasRelService;

    @RequestMapping(value = "/queryDeliveryWay")
    public String queryDeliveryWay(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        return doAdapte(requestMsg, responseMsg);

    }

    @Override
    protected void validateInputJson(RequestMsg requestMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        if (null == json) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 订单号必填
        ValidateUtil.validNotNull(json, "warehouseID");
        ValidateUtil.validMaxLength(json, "warehouseID", 10, true);

    }

    @Override
    public boolean checkCustomerTansferConfig(RequestMsg requestMsg, ResponseMsg responseMsg) {

        // JSONObject json =
        // JSONObject.parseObject(requestMsg.getData().toString());
        //
        // Bpartner bpartner =
        // CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        // Long warehouseId = json.getLongValue("warehouseID");
        // // 首先验证仓库是否存在
        // QueryWarhouseByIdCommand houseCommand = new
        // QueryWarhouseByIdCommand();
        // houseCommand.setWarehouseId(warehouseId);
        // WarehouseVo warehouseVo =
        // upsWarehouseService.queryWarehouseById(houseCommand);
        // if (null == warehouseVo) {
        // throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS,
        // warehouseId);
        // }
        //
        // String customerCode = bpartner.getValue();
        //
        // // 校验当前仓库和用户是否支持迁移
        // CustomerTansferConfigPkCommand command = new
        // CustomerTansferConfigPkCommand();
        // command.setWarehouseId(warehouseId);
        // command.setCustomerCode(customerCode);

        return true;
    }

    @Override
    public void doAdapteInOpenAPI(RequestMsg requestMsg, ResponseMsg responseMsg) {
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        Long warehouseId = json.getLongValue("warehouseID");
        QueryWarhouseByIdCommand houseCommand = new QueryWarhouseByIdCommand();
        houseCommand.setWarehouseId(warehouseId);
        WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseById(houseCommand);
        if (null == warehouseVo) {
            throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS, warehouseId);
        }
        ProductLogisticsCommand productCommand = new ProductLogisticsCommand();
        productCommand.setCustomerCode(bpartner.getValue());
        LogisticsDist dist = new LogisticsDist();
        dist.setLogisticsDistCode(warehouseVo.getCode());
        productCommand.setLocisticsDist(dist);
        List<ProductInstance> productList = productInstanceService.queryProductInstanceByLogistics(productCommand);
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        if (null != productList && productList.size() > 0) {
            for (ProductInstance productInstance : productList) {
                // 过滤掉没有适配的派送方式
                if (StringUtils.isBlank(productInstance.getDeliveryMode())) {
                    continue;
                }
                Map<String, Object> map = new HashMap<String, Object>();
                // 老接口派送方式为Long型
                try {
                    Long deliveryId = Long.valueOf(productInstance.getDeliveryMode());
                    map.put("deliveryID", deliveryId);
                } catch (NumberFormatException e) {
                    map.put("deliveryID", null);
                }
                map.put("deliveryWay", productInstance.getName());
                map.put("winitProductCode", productInstance.getCode());
                List<Map<String, Object>> vasData = buildVASInfo(productInstance.getCode());
                if (null != vasData && vasData.size() > 0) {
                    map.put("VASList", buildVASInfo(productInstance.getCode()));
                }

                map.put("warehouseID", warehouseId);
                map.put("isMandoorplateNumbers", "N");
                data.add(map);
            }
        }

        responseMsg.setData(data);

    }

    private List<Map<String, Object>> buildVASInfo(String instanceCode) {
        List<Map<String, Object>> vasMapList = new ArrayList<Map<String, Object>>();
        BaseVasRelQueryCommand command = new BaseVasRelQueryCommand();
        command.setCtx(CommandContext.getContext());
        BaseVasRelVo vo = new BaseVasRelVo();
        vo.setInstanceCode(instanceCode);
        vo.setType(PmsEnumType.BaseVasRelType.PSC_INSTANCE.getCode());
        vo.setIsActive(PmsConstants.ACTIVE_Y);
        command.setVo(vo);
        List<PlanEventVo> vasList = baseVasRelService.queryPlanEventListByProductCode(command);
        if (CollectionUtils.isEmpty(vasList)) {
            return null;
        }
        for (PlanEventVo planEventVo : vasList) {
            Map<String, Object> vasMap = new HashMap<String, Object>();
            List<BaseAttrRelVo> attrList = planEventVo.getAttrList();
            if (StringUtils.isNotBlank(planEventVo.getEventCode())) {
                vasMap.put("serviceCode", planEventVo.getEventCode());
                List<Map<String, Object>> attrMapList = new ArrayList<Map<String, Object>>();
                if (attrList != null && attrList.size() > 0) {

                    for (BaseAttrRelVo attr : attrList) {
                        Map<String, Object> attrMap = new HashMap<String, Object>();
                        attrMap.put("attrCode", attr.getAttrCode());
                        attrMap.put("attrUnit", attr.getUnit());
                        attrMap.put("maxValue", attr.getMaxValue());
                        attrMap.put("minValue", attr.getMinValue());
                        attrMapList.add(attrMap);
                    }

                }
                vasMap.put("attrList", attrMapList);
                vasMapList.add(vasMap);
            }

        }
        return vasMapList;

    }

    /**
     * 查询所有仓库的可用派送方式
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryAllDeliveryWay")
    public String queryAllDeliveryWay(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        QueryWarehouseByTypesCommand command = new QueryWarehouseByTypesCommand();
        command.setCtx(CommandContext.getContext());
        // 使用发货仓查询
        command.setTypes(Arrays.asList("CONSIGNMENT"));
        List<WarehouseVo> warehouseList = upsWarehouseService.queryWarehouseByTypes(command);
        if (CollectionUtils.isEmpty(warehouseList)) {
            throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS);
        }
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        List<Map<String, Object>> warehouseMapList = new ArrayList<Map<String, Object>>();
        for (WarehouseVo warehouseVo : warehouseList) {
            Map<String, Object> warehouseMap = new HashMap<String, Object>();
            ProductLogisticsCommand productCommand = new ProductLogisticsCommand();
            productCommand.setCustomerCode(bpartner.getValue());
            LogisticsDist dist = new LogisticsDist();
            dist.setLogisticsDistCode(warehouseVo.getCode());
            productCommand.setLocisticsDist(dist);
            List<ProductInstance> productList = productInstanceService.queryProductInstanceByLogistics(productCommand);
            List<Map<String, Object>> productMapList = new ArrayList<Map<String, Object>>();
            if (null != productList && productList.size() > 0) {
                for (ProductInstance productInstance : productList) {
                    // 过滤掉没有适配的派送方式
                    if (StringUtils.isBlank(productInstance.getDeliveryMode())) {
                        continue;
                    }
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("warehouseId", warehouseVo.getWarehouseId());
                    map.put("warehouseCode", warehouseVo.getCode());
                    map.put("warehouseName", warehouseVo.getName());
                    // 老接口派送方式为Long型
                    try {
                        Long deliveryId = Long.valueOf(productInstance.getDeliveryMode());
                        map.put("deliveryId", deliveryId);
                    } catch (NumberFormatException e) {
                        map.put("deliveryId", null);
                    }
                    map.put("deliveryWay", productInstance.getName());
                    map.put("winitProductCode", productInstance.getCode());
                    map.put("isPublic", productInstance.getIsActive());

                    productMapList.add(map);
                }
            }
            warehouseMap.put("warehouseName", warehouseVo.getName());
            warehouseMap.put("winitProductList", productMapList);
            warehouseMapList.add(warehouseMap);
        }

        responseMsg.setData(warehouseMapList);

        return SUCCESS;

    }
    
    /**
     * 根据仓库ID查询仓库下的PSC：开发者平台使用
     * @param requestMsg
     * @param responseMsg
     */
    @RequestMapping(value = "/queryDeliveryWayByWarehouseId")
    public String queryDeliveryWayByWarehouseId(RequestMsg requestMsg, ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        if (null == json) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        // 订单号必填
        ValidateUtil.validNotNull(json, "warehouseId");
        ValidateUtil.validMaxLength(json, "warehouseId", 10, true);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        Long warehouseId = json.getLongValue("warehouseId");
        QueryWarhouseByIdCommand houseCommand = new QueryWarhouseByIdCommand();
        houseCommand.setWarehouseId(warehouseId);
        WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseById(houseCommand);
        if (null == warehouseVo) {
            throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS, warehouseId);
        }
        ProductLogisticsCommand productCommand = new ProductLogisticsCommand();
        productCommand.setCustomerCode(bpartner.getValue());
        LogisticsDist dist = new LogisticsDist();
        dist.setLogisticsDistCode(warehouseVo.getCode());
        productCommand.setLocisticsDist(dist);
        List<ProductInstance> productList = productInstanceService.queryProductInstanceByLogistics(productCommand);
        Map<String, Object> warehouseMap = new HashMap<String, Object>();
        List<Map<String, Object>> productMapList = new ArrayList<Map<String, Object>>();
        if (null != productList && productList.size() > 0) {
            for (ProductInstance productInstance : productList) {
                // 过滤掉没有适配的派送方式
                if (StringUtils.isBlank(productInstance.getDeliveryMode())) {
                    continue;
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("warehouseId", warehouseVo.getWarehouseId());
                map.put("warehouseCode", warehouseVo.getCode());
                map.put("warehouseName", warehouseVo.getName());
                // 老接口派送方式为Long型
                try {
                    Long deliveryId = Long.valueOf(productInstance.getDeliveryMode());
                    map.put("deliveryId", deliveryId);
                } catch (NumberFormatException e) {
                    map.put("deliveryId", null);
                }
                map.put("deliveryWay", productInstance.getName());
                map.put("winitProductCode", productInstance.getCode());
                map.put("isPublic", productInstance.getIsActive());
                productMapList.add(map);
            }
        }
        warehouseMap.put("warehouseName", warehouseVo.getName());
        warehouseMap.put("winitProductList", productMapList);

        responseMsg.setData(warehouseMap);
        
        
        return SUCCESS;

    }

}
